<?php
  include_once('./config/config.php');
  include_once('./config/check.php');

  //加这个关键词的目的就是为了分开请求
  $action = isset($_GET['action']) ? $_GET['action'] : '';

  if($action == "check"){
    $result = ["success" => false, "msg" => ''];
    $name = empty($_POST['name']) ? '' : $_POST['name'];
  
    //根据用户名去判断这部门是否已经存在了
    $sql = "SELECT * FROM {$pre_}departments WHERE `name` = '$name' ";
    $data = find($sql);

    if ($data) {
      $result['success'] = false;
      $result['msg'] = '部门已存在';
    }
    else{
      $result['success'] = true;
      $result['msg'] = '部门不存在,可以注册';
    }
      //将PHP数据转换为json 
      echo json_encode($result);
      exit;
  }


  if(!empty($_POST)){
    $name = empty($_POST['name']) ? '' : $_POST['name'];
    //查询这个用户名是否存在，防止他验证后再次提交
    $sql = "SELECT * FROM `{$pre_}departments` WHERE `name` = '$name'";
    $department = find($sql);

    if($department){
      ShowMsg('部门已存在，请重新输入');
      exit;
    }
    // var_dump($department) ;
    // exit;

    // 组装数据
    $data = ['name' => $name];

    //add()插入到数据中
    $insert = add('departments', $data);
    if($insert){
      ShowMsg('部门添加成功','department.php');
      exit;
    }else{
      ShowMsg('部门添加失败');
      exit;
    }
  }
?>
<!DOCTYPE html>
<html lang="en">
  <head>
  <?php include_once('common/meta.php');?>
  </head>

  <!--[if lt IE 7 ]> <body class="ie ie6"> <![endif]-->
  <!--[if IE 7 ]> <body class="ie ie7 "> <![endif]-->
  <!--[if IE 8 ]> <body class="ie ie8 "> <![endif]-->
  <!--[if IE 9 ]> <body class="ie ie9 "> <![endif]-->
  <!--[if (gt IE 9)|!(IE)]><!--> 
  <body> 
  <!--<![endif]-->
    
    <?php include_once('common/header.php'); ?>

    <?php include_once('common/menu.php'); ?>

    <div class="content">
        <div class="header">
            <h1 class="page-title">发布文章</h1>
        </div>
        <ul class="breadcrumb">
            <li><a href="index.html">Home</a> <span class="divider">/</span></li>
            <li class="active">Index</li>
        </ul>

        <div class="container-fluid">
            <div class="row-fluid">
                    
                <div class="btn-toolbar">
                    <button class="btn btn-primary" onClick="location='department.php'"><i class="icon-list"></i>部门列表</button>
                  <div class="btn-group">
                  </div>
                </div>

                <div class="well">
                    <div id="myTabContent" class="tab-content">
                      <div class="tab-pane active in" id="home">
                        <form method="POST" enctype="multipart/form-data">
                            <label>添加部门</label>
                            <input type="text" name="name" class="input-xxlarge" required>
                            <span id="notice" style="color: red; display:none">部门已注册</span>
                            <label></label>
                            <input id="add" class="btn btn-primary" type="submit" value="提交" />
                        </form>
                      </div>
                  </div>
                </div>
                
                <?php include_once('common/footer.php'); ?>
                    
            </div>
        </div>
    </div>
  </body>
</html>
<?php include_once('common/script.php');?>
<script>
 $("input[name = 'name']").change(function(){
    //用户名
    var name = $(this).val();
    // 创建异步对象
    var ajax = new  XMLHttpRequest();
    //绑定请求状态  当请求被发送到服务器时，我们需要执行一些基于响应的任务
    ajax.onreadystatechange = function(){
      if(ajax.status == 200){
        // 将获取到的json变成js的数据类型
        var result = JSON.parse(ajax.responseText);
        if(result.success){
          //可以注册
          $("#notice").css({'display' : 'inline-block', 'color' : 'green'});
          $("#notice").html('用户不存在,可以注册');
          // disabled提交禁用,false不禁用
          $("#add").prop('disabled', false)
        }
        else
        {
          //不可以注册
          $("#notice").css({'display':'inline-block','color':'red'})
          $("#notice").html('该用户名已注册')
      
          // prop改变标签属性,disabled提交禁用,true禁用
          $("#add").prop('disabled', true)
        }
      }
    } 
    //发起请求  false 同步  true 异步
    ajax.open('post','departmentAdd.php?action=check', true)
    //post的请求一定要设置 http头信息
    ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    //发送请求，并传递数据
    ajax.send(`name=${name}`)
  })


</script>
